<?php

declare(strict_types=1);

namespace App\Middleware\Admin;

use App\Constants\ErrorCode;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Utils\MD5Token;
class VerifyTokenMiddleware implements MiddlewareInterface
{
    #[Inject]
    protected ContainerInterface $container;
    #[Inject]
    protected RequestInterface $request;
    #[Inject]
    protected HttpResponse $response;
    protected string $scene;
    #[Inject]
    protected MD5Token $md5Token;
    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
        $this->scene = "admin";
        $this->md5Token = new MD5Token();
    }

    /**
     * Notes:处理请求
     * 2025/7/10
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            $token = $this->request->header('X-Token','');
            if (empty($token)){
                throw new \Exception(ErrorCode::getMessage(ErrorCode::TOKEN_MISSING), ErrorCode::TOKEN_MISSING);
            }
            $admin = $this->md5Token->verifyToken($token);
            //刷新 token时效
            $this->md5Token->refreshToken($token);
            //将jwt解密数据写入request attribute,以便于在后续处理中获取
            $request = $request->withAttribute('admin', $admin);
            return $handler->handle($request);
        }catch (\Exception $e){
            return $this->response->json([
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                "data"=>(object)[]
            ]);
        }
    }
}
